import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/account_api.dart';
import 'package:sainbainu/common/apis/common_api.dart';
import 'package:sainbainu/common/enums/sms_type.dart';
import 'package:sainbainu/common/http/exception.dart';
import 'package:sainbainu/common/models/request/bind_mobile_request.dart';
import 'package:sainbainu/common/models/request/sms_request.dart';
import 'package:sainbainu/common/repositories/account_repository.dart';
import 'package:sainbainu/common/repositories/common_repository.dart';
import 'package:sainbainu/common/services/storage.dart';
import 'package:sainbainu/common/services/user.dart';
import 'package:sainbainu/common/utils/custom_exception.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/values/constant.dart';
import 'package:sainbainu/common/values/storage_keys.dart';

import 'index.dart';

class BindMobileController extends GetxController {
  BindMobileController();

  final state = BindMobileState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.mobileController = TextEditingController();
    state.codeController = TextEditingController();
    state.accountRepository = AccountRepository(AccountApi());
    state.commonRepository = CommonRepository(CommonApi());
    state.isUpdate.value = UserService.to.accountInfo.value.mobileFlag == 1;
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.mobileController.dispose();
    state.codeController.dispose();
    state.smsTimer?.cancel();
  }

  /// 倒计时
  void runSmsTimer() {
    state.isSending.value = true;
    state.smsTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (state.smsSeconds.value > 0) {
        state.smsSeconds.value--;
      } else {
        timer.cancel();
        state.isSending.value = false;
        state.smsSeconds.value = AppConstant.smsSeconds;
      }
    });
  }

  /// 获取验证码
  void sendCode() async {
    if (state.isSending.value) {
      return;
    }
    try {
      if (state.mobileController.text.isEmpty) {
        throw CustomException('请输入手机号码');
      }
      if (state.mobileController.text.length != AppConstant.mobileLength) {
        throw CustomException('手机号长度为${AppConstant.mobileLength}位');
      }
      LoadingUtil.showLoading(text: '获取中...');
      await state.commonRepository.sendSms(SmsRequest(
        mobile: state.mobileController.text,
        type: SmsType.bind,
      ));
      LoadingUtil.showSuccess('获取成功'.tr);
      runSmsTimer();
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } on CustomException catch (e) {
      LoadingUtil.showError(e.toString());
    } catch (e) {
      LoadingUtil.showError('出错啦～');
    }
  }

  /// 确认提交
  void handleSubmit() async {
    try {
      if (state.mobileController.text.isEmpty) {
        throw CustomException('请输入手机号码');
      }
      if (state.mobileController.text.length != AppConstant.mobileLength) {
        throw CustomException('手机号长度为${AppConstant.mobileLength}位');
      }
      if (state.codeController.text.isEmpty) {
        throw CustomException('请输入验证码');
      }
      LoadingUtil.showLoading(text: '提交中...');
      await state.accountRepository.bindMobile(BindMobileRequest(
        mobile: state.mobileController.text,
        smsCode: state.codeController.text,
      ));
      await UserService.to.getAccountInfo();
      LoadingUtil.showSuccess('手机绑定成功'.tr);
      Get.back();
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } on CustomException catch (e) {
      LoadingUtil.showError(e.toString());
    } catch (e) {
      LoadingUtil.showError('出错啦～');
    }
  }
}
